import { toInteger } from "lodash";
import { emailVerify } from "@/api/modules/code";
import { userModifyAccount } from "@/api/modules/user";
import { useState, useEffect } from "react";
import { getUserInfo } from "@/utils/getUserInfo";
import { setToken, setUserInfo } from "@/redux/modules/global/action";
import { connect } from "react-redux";
import type { userGetuserInfoReturnModel } from "@/api/modules/user";
import { Button, Form, Input, InputNumber, Mentions, message, Modal } from "antd";
import { EyeInvisibleOutlined, EyeTwoTone, FormOutlined } from "@ant-design/icons";
import { WxRules, WxMessages, convertWxValidateToAntdRules } from "@/utils/WxValidate";
import { COMMON_EMAIL_SUFFIXES } from "@/enums/index";
import { useNavigate } from "react-router-dom";
import "../index.less";
const Account = (props: any) => {
	const { setToken, userInfo, setUserInfo }: { userInfo: userGetuserInfoReturnModel; setUserInfo: Function; setToken: Function } =
		props;
	const navigate = useNavigate();
	/** 对话框 */
	const [form] = Form.useForm();
	const [dialogLoading, setDialogLoading] = useState<boolean>(false);
	enum DialogType {
		Null = "",
		Phone = "phone",
		Email = "email",
		Password = "password"
	}
	interface Dialog {
		visible: boolean;
		title: string;
		type: DialogType;

		phone: string;
		email: string;
		newEmail: string;
		newPassword: string;
		password: string;
		code: string;

		timer: number | string;
		codeText: string;
	}
	const [dialog, setDialog] = useState<Dialog>({
		visible: false,
		title: "",
		type: DialogType.Null, // 对话框类型

		phone: "", // 手机号/登陆账号
		email: "", // 邮箱地址
		newEmail: "", // 新邮箱地址
		newPassword: "", // 新密码
		password: "", // 确认密码
		code: "", // 验证码

		timer: "", // 定时器
		codeText: "获取验证码" // 验证码文本显示
	});
	function openDialog(type: DialogType) {
		// 打开对话框
		dialog.type = type;
		dialog.visible = true;
		dialog.phone = userInfo.phone;
		dialog.email = userInfo.email;
		switch (type) {
			case "phone":
				dialog.title = "修改手机号/登录账号";
				break;
			case "email":
				dialog.title = "修改绑定邮箱";
				break;
			case "password":
				dialog.title = "重置密码";
				break;
		}
		setDialog({ ...dialog });
	}
	function closeDialog() {
		// 关闭对话框
		clearInterval(dialog.timer as number); // 清空计时器
		form.resetFields();
		setDialog({
			visible: false,
			title: "",
			type: DialogType.Null, // 对话框类型

			phone: "", // 手机号/登陆账号
			email: "", // 邮箱地址
			newEmail: "", // 新邮箱地址
			newPassword: "", // 新密码
			password: "", // 确认密码
			code: "", // 验证码

			timer: 0, // 定时器
			codeText: "获取验证码" // 验证码文本显示
		});
	}
	// 发送验证码
	async function sendCode(email: string) {
		if (dialog.timer) {
			// 验证码已发送后不能再发送
			return;
		}
		const { code, msg } = await emailVerify({ email });
		if (code === 0) {
			message?.success(msg);
			setCodeTimer(); // 设置定时器
		}
	}
	// 设置计时器
	function setCodeTimer() {
		let ss = 300; // 5分钟
		dialog.codeText = formatDate(ss);

		dialog.timer = window.setInterval(() => {
			// 开始计时
			ss--;
			dialog.codeText = formatDate(ss);
			if (ss === 0) {
				// 计时器结束
				dialog.codeText = "重新发送";
				clearInterval(dialog.timer as number); // 清空计时器
				dialog.timer = "";
			}
			setDialog({ ...dialog });
		}, 1000);
	}
	// 格式化时间
	function formatDate(ssNum: number) {
		let min = 0; // 初始化分钟
		let ss = 0; // 初始化秒数
		if (ssNum > 60) {
			// 如果秒数大于60，将秒数转换成分钟数
			min = toInteger(ssNum / 60); // 获取分钟，除以60取整数，得到整数分钟
			ss = toInteger(ssNum % 60); // 获取秒数，秒数取佘，得到整数秒数
		} else {
			ss = toInteger(ssNum % 60); // 获取秒数，秒数取佘，得到整数秒数
		}
		return `${min.toString().padStart(2, "0")} : ${ss.toString().padStart(2, "0")}`;
	}
	// 点击确定按钮
	const handleDialogOk = () => {
		form.submit();
	};
	// 修改sku规格表单失败回调
	const onDialogFinishFailed = (errorInfo: any) => {
		message.warning("请检查表单填写是否正确！");
		console.log("Failed:", errorInfo);
	};
	// 提交新增/修改表单
	const onDialogFinish = async (form: any) => {
		console.log("form", form);
		modifyAccount(form);
	};
	async function modifyAccount(form: any) {
		try {
			setDialogLoading(true);
			// 修改账户接口
			const { code, msg } = await userModifyAccount({
				...dialog,
				...form
			});
			if (code === 0) {
				switch (dialog.type) {
					case "phone":
						logout();
						closeDialog();
						message?.success("修改手机号，请退出重新登陆");
						break;
					case "password":
						logout();
						closeDialog();
						message?.success("重置密码成功，请退出重新登陆");
						break;
					default:
						closeDialog();
						message?.success(msg);
						getUserInfo();
						break;
				}
			}
		} finally {
			setDialogLoading(false);
		}
	}
	function logout() {
		setToken("");
		setUserInfo(null);
		navigate("/login");
	}

	// 示例：微信小程序中的规则定义
	const wxRules: WxRules = {
		phone: { required: true, tel: true },
		newEmail: { required: true, email: true },
		newPassword: { required: true, minlength: 6 },
		password: { required: true, minlength: 6, equalTo: "newPassword" }
	};

	// 示例：自定义错误消息
	const wxMessages: WxMessages = {
		phone: {
			required: "请输入手机号/登陆账号",
			tel: "请输入正确的手机号/登陆账号"
		},
		newEmail: {
			required: "请输入邮箱地址",
			email: "请输入正确的邮箱地址"
		},
		newPassword: {
			required: "请输入密码",
			minlength: "密码长度不能小于6位"
		},
		password: {
			required: "请输入确认密码",
			minlength: "密码长度不能小于6位",
			equalTo: "两次输入的密码不一致"
		}
	};
	// 转换为Antd规则
	const antdRules = convertWxValidateToAntdRules(wxRules, wxMessages, form);
	console.log("antdRules", antdRules);
	return (
		<>
			<Form preserve={false} size="middle" autoComplete="off" layout={"vertical"}>
				<Form.Item label="手机号/登陆账号">
					<span className="text-16 tracking-widest">{userInfo.phone}</span>
					<Button type="primary" className="strong ml-20" icon={<FormOutlined />} onClick={() => openDialog(DialogType.Phone)}>
						修 改
					</Button>
				</Form.Item>
				<Form.Item label="绑定邮箱">
					<span className="text-16 tracking-widest">{userInfo.email}</span>
					<Button type="primary" className="strong ml-20" icon={<FormOutlined />} onClick={() => openDialog(DialogType.Email)}>
						修 改
					</Button>
				</Form.Item>
				<Form.Item label="账号密码">
					<span className="text-16 tracking-widest">*********</span>
					<Button type="primary" className="strong ml-20" icon={<FormOutlined />} onClick={() => openDialog(DialogType.Password)}>
						修 改
					</Button>
				</Form.Item>
			</Form>
			<Modal
				width={600}
				title={dialog.title}
				open={dialog.visible}
				destroyOnClose={true}
				onOk={handleDialogOk}
				confirmLoading={dialogLoading}
				onCancel={closeDialog}
				getContainer={false}
			>
				<Form
					form={form}
					preserve={false}
					size="middle"
					autoComplete="off"
					layout={"vertical"}
					onFinish={onDialogFinish}
					onFinishFailed={onDialogFinishFailed}
				>
					<Form.Item label="绑定邮箱">
						<span>{userInfo.email}</span>
					</Form.Item>
					{dialog.type === "phone" && (
						<Form.Item label="手机号/登陆账号" name="phone" rules={antdRules["phone"]}>
							<InputNumber stringMode controls={false} placeholder="输入新手机手机号" className="!w-full" />
						</Form.Item>
					)}
					{dialog.type === "email" && (
						<Form.Item label="新邮箱地址" name="newEmail" rules={antdRules["newEmail"]}>
							<Mentions
								placeholder="例如: 你的名字@gmail.com"
								autoSize
								className="!w-full"
								split={""}
								options={COMMON_EMAIL_SUFFIXES}
							/>
						</Form.Item>
					)}
					{dialog.type === "password" && (
						<>
							<Form.Item label="新账号密码" name="newPassword" rules={antdRules["newPassword"]}>
								<Input.Password placeholder="输入新账号密码" className="!w-full" maxLength={50} showCount />
							</Form.Item>
							<Form.Item label="确认密码" dependencies={["newPassword"]} name="password" rules={antdRules["password"]}>
								<Input.Password placeholder="输入确认密码" className="!w-full" maxLength={50} showCount />
							</Form.Item>
						</>
					)}
					<Form.Item label="邮箱验证码" name="code" rules={[{ required: true, message: "请输入邮箱验证码" }]}>
						<Input
							placeholder="输入邮箱验证码"
							maxLength={4}
							showCount
							className="code-input"
							addonAfter={
								<Button
									type="primary"
									disabled={dialog.timer ? true : false}
									className="!w-full"
									onClick={() => sendCode(userInfo.email)}
								>
									{dialog.codeText}
								</Button>
							}
						/>
					</Form.Item>
				</Form>
			</Modal>
		</>
	);
};
const mapState = (state: any) => ({
	userInfo: state.global.userInfo
});
const mapDispatchToProps = { setToken, setUserInfo };
export default connect(mapState, mapDispatchToProps)(Account);
